import AsyncStorage from "@react-native-async-storage/async-storage";
import logo from '../../assets/logo.png';
import bnblogo from '../Asset/bnb-logo.png';
import ethlogo from '../Asset/eth-logo.png';
//------------------------------------------------钱包与网络-----数据-------------
export const getIsLogin = async () => {
    try {
        await initNowWallet();
        return nowWallet.providerUrl !== "";

    }
    catch (e) {
        return false
    }
}
/*
    总体结构模型
*   1.链（名称Key，logo，主币名称，区块浏览器，主币和代币名称）
        1.1 多个providerUrl
        1.2 多个钱包（地址Key，私钥，钱包名称，钱包密码提示，密码）
    2.目前用的数据（链名称，providerUrl，钱包地址）
*/
//链的直接属性 唯一Key = `L2_chainBaseType_${chainID}`
//目前不单独存储 一起存储在 key = `L2_allChainBaseType`
export class chainBaseType {
    name:string = "";//链名称
    img:string = "";//链logo
    tipText:string = "";//链的主币/代币名称
    coinName:string= "";//主币名称
    blockNet:string = "";//区块浏览器地址
    blockNetApi:string = "";//区块浏览器Api
    blockNetKey:string = "";//区块浏览器的Key
    chainID:string = "";//链的ID Key
}
//链所拥有的数据 唯一Key = `L2_chainInfoType_${chainID}`
export class chainInfoType {
    chainID:string = ""//链的名称 Key
    providerUrlList:string[] = [];//链所属的providerUrlList
    walletList:string[] = [];//链下面的钱包地址,
    selectedProviderUrl:string = "";//选中的链的providerUrl
    userProviderUrlList:string[] = [];//用户添加的链的providerUrlList
}
//节点数据 唯一Key = `L2_providerInfoType_${providerUrl}`
export class providerInfoType {
    providerUrl:string = "";
    name:string = ""
}
//钱包的数据 唯一key = `L2_walletInfoType_${chainID}_${address}`
export class walletInfoType {
    chainID:string = "";//所属链的ID
    address:string = "";//钱包地址
    privateKey:string = "";//钱包私钥
    walletName:string = "";//钱包名称
    tip:string = "";//钱包密码提示
    password:string ="";//钱包密码
    mnemonic:string = "";//钱包助记词
    balance:string = "0";//钱包余额
}
//目前所用的链和钱包和providerUrl 唯一key = `L2_useWalletType`
export class useWalletType {
    chainID:string = "";//链名称
    providerUrl:string = "";//链所属的providerUrl
    address:string = "";//钱包地址
}

export let nowWallet:useWalletType = {chainID:"",providerUrl:"",address:""};//正在使用中的地址
//初始化 目前所用的链和钱包和providerUrl
export const initNowWallet = async () => {
    let useWalletNetStr = await AsyncStorage.getItem("L2_useWalletType");
    console.log(`useWalletNetStr=${useWalletNetStr}`)
    if(useWalletNetStr)
    {
        nowWallet = JSON.parse(useWalletNetStr) ;
        return nowWallet;
    }

    nowWallet = {chainID:"",providerUrl:"",address:""}
    return nowWallet;
}
//更新   目前所用的链和钱包和providerUrl
export const updateNowWallet = async (newNowWalletNet:useWalletType) => {
    try {
        nowWallet = newNowWalletNet;
        await AsyncStorage.setItem("L2_useWalletType", JSON.stringify(newNowWalletNet));
        return true
    }catch (e) {
        return false
    }
}
//清除   目前所用的链和钱包和providerUrl
export const clearNowWallet = async () => {
    try {
        nowWallet = {chainID:"",providerUrl:"",address:""};
        await AsyncStorage.setItem("L2_useWalletType", JSON.stringify(nowWallet));
        return true
    }catch (e) {
        return false
    }
}


//目前添加进来的所有网络
let netList:chainBaseType[] = [];
//初始化 所拥有的链
export const initNet = async () => {
    //初始化一些基本数据
    let initNetChainInfo = await AsyncStorage.getItem(`L2_initNetChainInfo`);
    if(!initNetChainInfo || Number(initNetChainInfo) < 1)
    {
        await addChainInfo({chainID:"123778899",providerUrlList:["http://123.58.210.13:8546"],walletList:[],selectedProviderUrl:"",userProviderUrlList:[]})
        await addChainInfo({chainID:"56",providerUrlList:["https://bsc-dataseed4.ninicoin.io"],walletList:[],selectedProviderUrl:"",userProviderUrlList:[]})
        await addChainInfo({chainID:"1",providerUrlList:["https://web3.mytokenpocket.vip"],walletList:[],selectedProviderUrl:"",userProviderUrlList:[]})
        await addChainInfo({chainID:"123778899",providerUrlList:[],walletList:[],selectedProviderUrl:"http://123.58.210.13:8546",userProviderUrlList:[]})
        await addChainInfo({chainID:"56",providerUrlList:[],walletList:[],selectedProviderUrl:"https://bsc-dataseed4.ninicoin.io",userProviderUrlList:[]})
        await addChainInfo({chainID:"1",providerUrlList:[],walletList:[],selectedProviderUrl:"https://web3.mytokenpocket.vip",userProviderUrlList:[]})
        await AsyncStorage.setItem(`L2_initNetChainInfo`,"1")
    }
    let netListStr = await AsyncStorage.getItem("L2_allChainBaseType");
    if(netListStr)
    {
        netList = JSON.parse(netListStr);
        return netList;
    }
    netList = [
        {
            name:"SmartX_L2",
            img:logo,
            tipText:"SL2/ERC20",
            coinName:"SL2",
            blockNet:"http://101.36.125.99:4000",
            blockNetApi:"http://101.36.125.99:4000/api",
            blockNetKey:"",
            chainID:"123778899"
        },
        {
            name:"BSC",
            img:bnblogo,
            tipText:"BSC/BEP20",
            coinName:"BNB",
            blockNet:"https://bscscan.com",
            blockNetApi:"https://api.bscscan.com/api",
            blockNetKey:"Q2DYXJRUGJKS5TYF6PW7SCGM7KNCPPUZXV",
            chainID:"56"
        },
        {
            name:"ETH",
            img:ethlogo,
            tipText:"ETH/ERC20",
            coinName:"ETH",
            blockNet:"https://cn.etherscan.com",
            blockNetApi:"https://api.etherscan.io/api",
            blockNetKey:"PJ6GNDT552KAC368IRCCBX3VISJ5P6XE61",
            chainID:"1"
        }
    ];
    return netList;
}

//添加   链的基本信息 false 为已添加chainID已有了
export const addChainBase = async (chain:chainBaseType) => {
    try {
        await initNet();
        let index = netList.findIndex(item => {
            return (item.chainID === chain.chainID)
        })
        if (index !== -1 || index === undefined) {
            return false
        }
        netList.push(chain)
        await AsyncStorage.setItem("L2_allChainBaseType", JSON.stringify(netList));
        return true
    }
    catch (e) {
        return false
    }
}
//移除   链的基本信息
export const removeChainBase = async (chain:chainBaseType) => {
    try {
        await initNet();
        let index = netList.findIndex(item => {
            return (item.name === chain.name && item.chainID === chain.chainID)
        })
        if (index === -1 || index === undefined) {
            return false
        }
        netList.splice(index, 1)
        await AsyncStorage.setItem("L2_allChainBaseType", JSON.stringify(netList));
        return true
    }
    catch (e) {
        return false
    }
}
//获取   链的基本信息 通过ID
export const getChainBaseByChainID = async (chainID:string) => {
    await initNet();
    let index = netList.findIndex(item => {return item.chainID === chainID});
    if(index !== -1)
    {
        return netList[index];
    }
    return null;
}

//
export const ETH_more_Logo = 'https://icons.veryicon.com/png/o/business/digital-currency/eth-1.png';
//添加修改   链的拥有信息
export const addChainInfo = async (chainInfo:chainInfoType) => {
    let chainInfoTemp:chainInfoType = {chainID:"",providerUrlList:[],walletList:[],selectedProviderUrl:"",userProviderUrlList:[]};
    let chainSaveStr = await AsyncStorage.getItem(`L2_chainInfoType_${chainInfo.chainID}`)
    if (!chainSaveStr)
    {
        await AsyncStorage.setItem(`L2_chainInfoType_${chainInfo.chainID}`,JSON.stringify(chainInfo))
        return {success:true};
    }
    chainInfoTemp = JSON.parse(chainSaveStr);
    if(chainInfo.providerUrlList.length > 0)
    {
        for(let i = 0 ; i < chainInfo.providerUrlList.length ; i++)
        {
            let index = chainInfoTemp.providerUrlList.indexOf(chainInfo.providerUrlList[i]);
            if(index !== -1)
            {
                return {success:false,falseReason:chainInfo.providerUrlList[i]+" providerUrl 已存在"};
            }
            chainInfoTemp.providerUrlList.push(chainInfo.providerUrlList[i]);
        }
        await AsyncStorage.setItem(`L2_chainInfoType_${chainInfoTemp.chainID}`,JSON.stringify(chainInfoTemp))
        return {success:true};
    }
    if(chainInfo.walletList.length > 0)
    {
        for(let i = 0 ; i < chainInfo.walletList.length ; i++)
        {
            let index = chainInfoTemp.walletList.indexOf(chainInfo.walletList[i]);
            if(index !== -1)
            {
                return {success:false,falseReason:chainInfo.walletList[i]+" 地址已存在"};
            }
            chainInfoTemp.walletList.push(chainInfo.walletList[i]);
        }
        await AsyncStorage.setItem(`L2_chainInfoType_${chainInfoTemp.chainID}`,JSON.stringify(chainInfoTemp))
        return {success:true};
    }
    if(chainInfo.userProviderUrlList.length > 0)
    {
        for(let i = 0 ; i < chainInfo.userProviderUrlList.length ; i++)
        {
            let index = chainInfoTemp.userProviderUrlList?chainInfoTemp.userProviderUrlList.indexOf(chainInfo.userProviderUrlList[i]) : -1;
            if(index !== -1)
            {
                return {success:false,falseReason:chainInfo.userProviderUrlList[i]+" 节点已存在"};
            }
            let addProviderUrlInfoRes =  await addProviderUrlInfo({providerUrl:chainInfo.userProviderUrlList[i],name:""})
            if(!addProviderUrlInfoRes.success)
            {
                return addProviderUrlInfoRes;
            }
            if(!chainInfoTemp.userProviderUrlList)
            {
                chainInfoTemp.userProviderUrlList = [];
            }
            chainInfoTemp.userProviderUrlList.push(chainInfo.userProviderUrlList[i]);
        }
        await AsyncStorage.setItem(`L2_chainInfoType_${chainInfoTemp.chainID}`,JSON.stringify(chainInfoTemp))
        return {success:true};
    }
    if(chainInfo.selectedProviderUrl)
    {
        chainInfoTemp.selectedProviderUrl = chainInfo.selectedProviderUrl;
        await AsyncStorage.setItem(`L2_chainInfoType_${chainInfoTemp.chainID}`,JSON.stringify(chainInfoTemp))
        return {success:true};
    }
    return {success:false,falseReason:"请输入添加信息"};
}
//移除   链的拥有信息
export const removeChainInfo = async (chainInfo:chainInfoType) => {
    let chainInfoTemp:chainInfoType = {chainID:"",providerUrlList:[],walletList:[],selectedProviderUrl:"",userProviderUrlList:[]};
    let chainSaveStr = await AsyncStorage.getItem(`L2_chainInfoType_${chainInfo.chainID}`)
    if (!chainSaveStr)
    {
        return {success:false,falseReason:"未找到该链信息"};
    }
    chainInfoTemp = JSON.parse(chainSaveStr);
    if(chainInfo.providerUrlList.length > 0)
    {
        for(let i = 0 ; i < chainInfo.providerUrlList.length ; i++)
        {
            let index = chainInfoTemp.providerUrlList.indexOf(chainInfo.providerUrlList[i]);
            if(index === -1)
            {
                return {success:false,falseReason:chainInfo.providerUrlList[i]+" providerUrl 不存在"};
            }
            chainInfoTemp.providerUrlList.splice(i,1);
        }
        await AsyncStorage.setItem(`L2_chainInfoType_${chainInfoTemp.chainID}`,JSON.stringify(chainInfoTemp))
        return {success:true};
    }
    if(chainInfo.walletList.length > 0)
    {
        for(let i = 0 ; i < chainInfo.walletList.length ; i++)
        {
            let index = chainInfoTemp.walletList.indexOf(chainInfo.walletList[i]);
            if(index === -1)
            {
                return {success:false,falseReason:chainInfo.walletList[i]+" 地址不存在"};
            }
            chainInfoTemp.walletList.splice(index,1);
        }
        await AsyncStorage.setItem(`L2_chainInfoType_${chainInfoTemp.chainID}`,JSON.stringify(chainInfoTemp))
        return {success:true};
    }
    if(chainInfo.userProviderUrlList.length > 0)
    {
        for(let i = 0 ; i < chainInfo.userProviderUrlList.length ; i++)
        {
            let index = chainInfoTemp.userProviderUrlList.indexOf(chainInfo.userProviderUrlList[i]);
            if(index === -1)
            {
                return {success:false,falseReason:chainInfo.userProviderUrlList[i]+" 节点不存在"};
            }
            let removeProviderUrlInfoRes = await removeProviderUrlInfo(chainInfoTemp.userProviderUrlList[i])
            if(!removeProviderUrlInfoRes.success)
            {
                return removeProviderUrlInfoRes;
            }
            chainInfoTemp.userProviderUrlList.splice(i,1);

        }
        await AsyncStorage.setItem(`L2_chainInfoType_${chainInfoTemp.chainID}`,JSON.stringify(chainInfoTemp))
        return {success:true};
    }
    if(chainInfo.selectedProviderUrl)
    {
        chainInfoTemp.selectedProviderUrl = chainInfo.selectedProviderUrl;
        await AsyncStorage.setItem(`L2_chainInfoType_${chainInfoTemp.chainID}`,JSON.stringify(chainInfoTemp))
        return {success:true};
    }
    return {success:false,falseReason:"请输入删除信息"};
}
//获取   链的拥有信息
export const getChainInfo = async (chainID:string) => {
    let chainInfoTemp:chainInfoType = {chainID:chainID,providerUrlList:[],walletList:[],selectedProviderUrl:"",userProviderUrlList:[]};
    let chainSaveStr = await AsyncStorage.getItem(`L2_chainInfoType_${chainID}`)
    if (!chainSaveStr)
    {
        return chainInfoTemp;
    }
    chainInfoTemp = JSON.parse(chainSaveStr);
    return chainInfoTemp;
}
//修改所有没有logo的链的url
export const initETH_More_Logo = async () => {
    let Keys = await AsyncStorage.getAllKeys()
    for (let i = 0; i < Keys.length; i++) {
        if (Keys[i] === "L2_allChainBaseType" ) {
            let value = await AsyncStorage.getItem(Keys[i]);
            if(value)
            {
                let value_json:chainBaseType[] = JSON.parse(value)

                for(let i = 0 ;i < value_json.length ; i++) {
                    console.log(value_json[i].chainID, ["123778899", "56", "1"].indexOf(value_json[i].chainID) === -1)
                    if(["123778899","56","1"].indexOf(value_json[i].chainID)===-1)
                    {
                        value_json[i].img = ETH_more_Logo;
                    }
                }
                await AsyncStorage.setItem(Keys[i],JSON.stringify(value_json))
            }
        }
    }
}

//添加   钱包的信息
export const addWalletInfo= async (walletInfo:walletInfoType) => {
    let walletStr = await AsyncStorage.getItem(`L2_walletInfoType_${walletInfo.chainID}_${walletInfo.address}`)
    if(!walletStr)
    {
        await AsyncStorage.setItem(`L2_walletInfoType_${walletInfo.chainID}_${walletInfo.address}`,JSON.stringify(walletInfo))
        return {success:true}
    }
    return {success:false,falseReason:"钱包已存在"}
}
//移除   钱包的信息
export const removeWalletInfo= async (walletInfo:walletInfoType) => {
    let walletStr = await AsyncStorage.getItem(`L2_walletInfoType_${walletInfo.chainID}_${walletInfo.address}`)
    if(walletStr)
    {
        await AsyncStorage.removeItem(`L2_walletInfoType_${walletInfo.chainID}_${walletInfo.address}`)
        return {success:true}
    }
    return {success:false,falseReason:"钱包不存在"}
}
//获取   钱包的信息
export const getWalletInfo= async (chainID:string, address:string) => {
    let walletStr = await AsyncStorage.getItem(`L2_walletInfoType_${chainID}_${address}`)
    console.log(`getWalletInfo:${walletStr}`)
    if(walletStr)
    {
        return JSON.parse(walletStr)
    }
    return null;
}
//修改   钱包的信息
export const updateWalletInfo= async (walletInfo:walletInfoType) => {
    let walletStr = await AsyncStorage.getItem(`L2_walletInfoType_${walletInfo.chainID}_${walletInfo.address}`)
    console.log(`updateWalletInfo:${walletStr}`)
    if(walletStr)
    {
        let oldWalletInfo =  JSON.parse(walletStr)
        await AsyncStorage.setItem(`L2_walletInfoType_${walletInfo.chainID}_${walletInfo.address}`,JSON.stringify(walletInfo));
        return {success:true}
    }
    return {success:false,falseReason:"钱包不存在"};
}

//添加钱包到链上   false 为已存在或者出问题了
export const addWallet = async (walletInfo:walletInfoType) => {
    try {
        let chainInfoTemp:chainInfoType = {chainID:walletInfo.chainID,providerUrlList:[],walletList:[walletInfo.address],selectedProviderUrl:"",userProviderUrlList:[]};
        let addChainInfoRes = await addChainInfo(chainInfoTemp);
        if(!addChainInfoRes.success)
        {
            return addChainInfoRes;
        }
        let addWalletInfoRes = await addWalletInfo(walletInfo);
        if(!addWalletInfoRes)
        {
            await removeChainInfo(chainInfoTemp);
            return addWalletInfoRes;
        }
        return {success:true}
    }catch (e) {
        return {success:false,falseReason:e.message.toString()}
    }
}
//移除钱包在链上   false 为已存在或者出问题了
export const removeWallet = async (walletInfo:walletInfoType) => {
    console.log(`removeWallet`,walletInfo)
    try{
        let chainInfoTemp:chainInfoType = {chainID:walletInfo.chainID,providerUrlList:[],walletList:[walletInfo.address],selectedProviderUrl:"",userProviderUrlList:[]};
        let addChainInfoRes = await removeChainInfo(chainInfoTemp);
        if(!addChainInfoRes.success)
        {
            return addChainInfoRes;
        }
        let addWalletInfoRes = await removeWalletInfo(walletInfo);
        if(!addWalletInfoRes.success)
        {
            await addChainInfo(chainInfoTemp);
            return addWalletInfoRes;
        }
        return {success:true}
    }catch (e) {
        return {success:false,falseReason:e.message.toString()}
    }
}
//添加   一条链
export const addChain = async (chainBase:chainBaseType,chainInfo:chainInfoType) =>
{
    let chainBaseTemp = await getChainBaseByChainID(chainBase.chainID)
    if(chainBaseTemp)
    {
        return {success:false,falseReason:"链已添加，请勿重复添加"}
    }
    let addChainInfoRes = await addChainInfo(chainInfo)
    if(!addChainInfoRes.success)
    {
        return addChainInfoRes;
    }
    let addChainBaseRes = await addChainBase(chainBase);
    if(!addChainBaseRes)
    {
        return {success:false,falseReason:"链已添加，请勿重复添加"};
    }
    return {success:true}

}
//移除   一条链
export const removeChain = async (chainBase:chainBaseType,chainInfo:chainInfoType) =>
{
    let chainBaseTemp = await getChainBaseByChainID(chainBase.chainID)
    if(!chainBaseTemp)
    {
        return {success:false,falseReason:"链未添加"}
    }
    let getChainInfoRes = await getChainInfo(chainBase.chainID)
    if(getChainInfoRes.walletList.length > 0)
    {
       return {success:false,falseReason:"链上还有未删除的钱包，暂时不能删除"}
    }
    let removeChainBaseRes = await removeChainBase(chainBase)
    if(!removeChainBaseRes)
    {
        return {success:false,falseReason:"链未添加"}
    }
    let removeChainInfoRes = await removeChainInfo(chainInfo)
    if(!removeChainInfoRes.success)
    {
        return removeChainInfoRes
    }
    return {success:true}

}

//添加   节点的信息 isUserNewNode一般为true
export const addProviderUrlInfo = async (providerInfo:providerInfoType) => {
    try {
        let providerUrlInfoStr = await AsyncStorage.getItem(`L2_providerInfoType_${providerInfo.providerUrl}`)
        if (providerUrlInfoStr) {
            return {success: false, falseReason: "节点信息已存在"}
        }
        await AsyncStorage.setItem(`L2_providerInfoType_${providerInfo.providerUrl}`, JSON.stringify(providerInfo))
        return {success: true}
    }
    catch (e) {
        return {success: false, falseReason: e.message}
    }
}
//移除   节点的信息
export const removeProviderUrlInfo = async (providerUrl:string) => {
    try {
        let providerUrlInfoStr = await AsyncStorage.getItem(`L2_providerInfoType_${providerUrl}`)
        if (providerUrlInfoStr) {
            await AsyncStorage.removeItem(`L2_providerInfoType_${providerUrl}`)
            return {success: true}
        }
        return {success: false, falseReason: "节点信息不存在"}
    }
    catch (e) {
        return {success: false, falseReason: e.message}
    }
}
//获取   节点的信息
export const getProviderUrlInfo = async (providerUrl:string) => {
    try {
        let providerUrlInfoStr = await AsyncStorage.getItem(`L2_providerInfoType_${providerUrl}`)
        if (providerUrlInfoStr) {
            let res:providerInfoType = JSON.parse(providerUrlInfoStr);
            return res;
        }
        let res:providerInfoType = {providerUrl,name:""}
        return res
    }
    catch (e) {
        console.log(`getProviderUrlInfo:`,e)
        return null
    }
}
//更新   节点的信息
export const updateProviderUrlInfo = async (providerInfo:providerInfoType) => {
    try {
        await AsyncStorage.setItem(`L2_providerInfoType_${providerInfo.providerUrl}`, JSON.stringify(providerInfo))
        return {success: true}
    }
    catch (e) {
        return {success: false, falseReason: e.message}
    }
}
//初始化 节点的选中节点
export const initAllProviderUrlInfo = async () => {
    let netListTemp = await initNet()
    for(let i = 0 ; i < netListTemp.length ; i++)
    {
        let chainID = netListTemp[i].chainID;
        console.log(chainID)
        let chainInfo = {chainID:chainID,providerUrlList:[],walletList:[],selectedProviderUrl:"",userProviderUrlList:[]};
        let chainInfoTemp = await getChainInfo(chainID)
        chainInfo.selectedProviderUrl = chainInfoTemp.providerUrlList[0];
        console.log(chainInfo)
        await addChainInfo(chainInfo)
        await updateProviderUrlInfo({providerUrl:chainInfoTemp.providerUrlList[0],name:netListTemp[i].name+"-1"})
    }
}

//------------------------------------------------资产与代币-----数据-------------
//key = `L2_tokenList_${chainID}_${walletAddress}`
export type tokenListNetType = {
    chainID:string,
    walletAddress:string,
    tokenAddressList:string[],
}

export const getTokenListByChainID = async (chainID:string, walletAddress:string) => {
    let res:tokenListNetType = {chainID:chainID,tokenAddressList:[],walletAddress};
    let resStr = await AsyncStorage.getItem(`L2_tokenList_${chainID}_${walletAddress}`);
    if(resStr)
    {
        res = JSON.parse(resStr);
    }
    return res;
}
export const addTokenToTokenList = async (chainID:string,tokenAddress:string,walletAddress:string) => {
    let tokenListNetTemp = await getTokenListByChainID(chainID,walletAddress);
    if(tokenListNetTemp.tokenAddressList.length === 0)
    {
        tokenListNetTemp.tokenAddressList.push(tokenAddress)
        await AsyncStorage.setItem(`L2_tokenList_${chainID}_${walletAddress}`,JSON.stringify(tokenListNetTemp));
        return {success:true}
    }
    let index = tokenListNetTemp.tokenAddressList.indexOf(tokenAddress);
    if(index > -1)
    {
        return {success:false,falseReason:"代币地址已添加"}
    }
    tokenListNetTemp.tokenAddressList.push(tokenAddress)
    await AsyncStorage.setItem(`L2_tokenList_${chainID}_${walletAddress}`,JSON.stringify(tokenListNetTemp));
    return {success:true}
}
export const removeTokenToFromTokenList = async (chainID:string,tokenAddress:string,walletAddress:string) => {
    let tokenListNetTemp = await getTokenListByChainID(chainID,walletAddress);
    if(tokenListNetTemp.tokenAddressList.length === 0)
    {
        return {success:false,falseReason:"代币地址未添加"}
    }
    let index = tokenListNetTemp.tokenAddressList.indexOf(tokenAddress);
    if(index === -1)
    {
        return {success:false,falseReason:"代币地址未添加"}
    }
    tokenListNetTemp.tokenAddressList.splice(index,1)
    await AsyncStorage.setItem(`L2_tokenList_${chainID}_${walletAddress}`,JSON.stringify(tokenListNetTemp));
    return {success:true}
}

//key = `L2_token_${chainID}_${tokenAddress}_${walletAddress}`
export type tokenNetType = {
    chainID:string,
    tokenSymbloName:string,
    tokenName:string,
    tokenAddress:string,
    tokenImg:string,
    tokenPrice_CNY:string,
    tokenPrice_USDT:string,
    balance:string,
    walletAddress:string
}

export const getTokenByChainID = async (chainID:string, tokenAddress:string, walletAddress:string) => {
    let res:tokenNetType = {
        chainID:chainID,
        tokenSymbloName:"",
        tokenName:"",
        tokenAddress:tokenAddress,
        tokenImg:"",
        tokenPrice_CNY:"",
        tokenPrice_USDT:"",
        balance:"",
        walletAddress
    };
    let resStr = await AsyncStorage.getItem(`L2_token_${chainID}_${tokenAddress}_${walletAddress}`);
    if(resStr)
    {
        res = JSON.parse(resStr);
        return res;
    }
    return null;
}
export const addTokenNet = async (chainID:string, tokenNet:tokenNetType, walletAddress:string) => {
    let tokenNetTemp:tokenNetType|null = await getTokenByChainID(chainID,tokenNet.tokenAddress,walletAddress);
    if(tokenNetTemp)
    {
        return {success:false,falseReason:"代币详情已经添加"}
    }
    await AsyncStorage.setItem(`L2_token_${chainID}_${tokenNet.tokenAddress}_${walletAddress}`,JSON.stringify(tokenNet));
    return {success:true};


}
export const removeTokenNet = async (chainID:string,tokenAddress:string,walletAddress:string) => {
    let tokenNetTemp:tokenNetType|null = await getTokenByChainID(chainID,tokenAddress,walletAddress);
    if(!tokenNetTemp)
    {
        return {success:false,falseReason:"代币详情未添加"}
    }
    await AsyncStorage.removeItem(`L2_token_${chainID}_${tokenAddress}_${walletAddress}`);
    return {success:true};
}
//更新代币详情
export const updateTokenNet = async (chainID:string, tokenNet:tokenNetType, walletAddress:string) => {
    let tokenNetTemp:tokenNetType|null = await getTokenByChainID(chainID,tokenNet.tokenAddress,walletAddress);
    if(!tokenNetTemp)
    {
        return {success:false,falseReason:"代币详情未添加"}
    }
    await AsyncStorage.setItem(`L2_token_${chainID}_${tokenNet.tokenAddress}_${walletAddress}`,JSON.stringify(tokenNet));
    return {success:true};
}
//添加代币
export const addTokenToChain = async (chainID:string, tokenNet:tokenNetType, walletAddress:string) => {
    let addTokenNetRes = await addTokenNet(chainID,tokenNet,walletAddress);
    if (!addTokenNetRes.success)
    {
        return addTokenNetRes;
    }
    let addTokenToTokenListRes = await addTokenToTokenList(chainID,tokenNet.tokenAddress,walletAddress)
    if(!addTokenToTokenListRes.success)
    {
        return addTokenToTokenListRes
    }
    return {success:true}
}
//移除代币
export const removeTokenFromChain = async (chainID:string,tokenAddress:string,walletAddress:string) => {
    let removeTokenNetRes = await removeTokenNet(chainID,tokenAddress,walletAddress);
    if (!removeTokenNetRes.success)
    {
        return removeTokenNetRes;
    }
    let removeTokenToFromTokenListRes = await removeTokenToFromTokenList(chainID,tokenAddress,walletAddress)
    if(!removeTokenToFromTokenListRes.success)
    {
        return removeTokenToFromTokenListRes
    }
    return {success:true}
}

//------------------------------------------------密码与检查-----数据-------------

export const checkWalletPassword = async (chainID:string,walletAddress:string,password:string) => {
    console.log(chainID,walletAddress,password)
    let walletInfo = await getWalletInfo(chainID,walletAddress);
    if(!walletInfo)
    {
        return {success:false,falseReason:"钱包不存在"}
    }
    if(password!==walletInfo.password)
    {
        return {success:false,falseReason:"密码错误"}
    }
    return {success:true}
}

//key = `L2_walletUseFinger_${chainID}__${walletAddress}`
export type walletUseFingerType = {
    chainID:string,
    walletAddress:string,
    useFinger:boolean
}
export const getWalletUseFinger = async (chainID:string,walletAddress:string) => {
    let walletUseFingerStr = await AsyncStorage.getItem(`L2_walletUseFinger_${chainID}__${walletAddress}`)
    if(!walletUseFingerStr)
    {
        return false
    }
    let walletUseFingerTemp:walletUseFingerType = JSON.parse(walletUseFingerStr);
    return walletUseFingerTemp.useFinger;
}
export const updateWalletUseFinger = async (chainID:string,walletAddress:string,useFinger:boolean) => {
    try {
        let walletUseFingerTemp: walletUseFingerType = {chainID, walletAddress, useFinger}
        await AsyncStorage.setItem(`L2_walletUseFinger_${chainID}__${walletAddress}`, JSON.stringify(walletUseFingerTemp))
        return {success:true};
    }catch (e) {
        console.log(`updateWalletUseFingerError:`,e)
        return {success:false,falseReason:e.message};
    }

}

//------------------------------------------------转账历史记录-----------------------
//唯一Key `L2_tranHistory_${chainID}_${address}`
export type tranHistoryType = {
    chainID:string,
    address:string,
    hashList:string[],
    toAddressList:L2_toAddressType[]
}
//转账对象
export type L2_toAddressType = {
    toAddress:string,
    timestamp:string
}

//获取   转账历史的所有hash
export const getTranHistoryHashList = async (chainID: string, address: string) => {
    let tranHistoryStr = await AsyncStorage.getItem(`L2_tranHistory_${chainID}_${address}`);
    if(!tranHistoryStr)
    {
        return [];
    }
    let tranHistoryTemp:tranHistoryType = JSON.parse(tranHistoryStr);
    return tranHistoryTemp.hashList;
}
//添加   转账历史的hash
export const addTranHistoryHashList = async (chainID: string, address: string, hash:string) => {
    let tranHistoryStr = await AsyncStorage.getItem(`L2_tranHistory_${chainID}_${address}`);
    if(!tranHistoryStr)
    {
        let res:tranHistoryType = {chainID,address,hashList:[hash],toAddressList:[]}
        await AsyncStorage.setItem(`L2_tranHistory_${chainID}_${address}`,JSON.stringify(res))
        return {success:true};
    }
    let res:tranHistoryType = JSON.parse(tranHistoryStr);
    if(res.hashList.indexOf(hash) >= 0)
    {
        return {success:false,falseReason:"该交易以添加"}
    }
    res.hashList.push(hash);
    await AsyncStorage.setItem(`L2_tranHistory_${chainID}_${address}`,JSON.stringify(res));
    return {success:true};
}
//移除   转账历史的hash  暂时不需要

//获取   转账历史的转账对象（通讯录）
export const getTranHistoryToAddressList = async (chainID: string, address: string) => {
    let tranHistoryStr = await AsyncStorage.getItem(`L2_tranHistory_${chainID}_${address}`);
    if(!tranHistoryStr)
    {
        return [];
    }
    let tranHistoryTemp:tranHistoryType = JSON.parse(tranHistoryStr);
    return tranHistoryTemp.toAddressList;
}
//添加   转账历史的转账对象
export const addTranHistoryToAddress = async (chainID: string, address: string, toAddressInfo:L2_toAddressType) => {
    let tranHistoryStr = await AsyncStorage.getItem(`L2_tranHistory_${chainID}_${address}`);
    if(!tranHistoryStr)
    {
        let res:tranHistoryType = {chainID,address,hashList:[],toAddressList:[toAddressInfo]}
        await AsyncStorage.setItem(`L2_tranHistory_${chainID}_${address}`,JSON.stringify(res))
        return {success:true};
    }
    let res:tranHistoryType = JSON.parse(tranHistoryStr);
    let index = res.toAddressList.findIndex((item)=>{return item.toAddress === toAddressInfo.toAddress})
    //如果已存在
    if(index >= 0)
    {
        res.toAddressList[index] = toAddressInfo;
        res.toAddressList.sort(function (x, y) {
            return Number(x.timestamp)-Number(y.timestamp);
        })
        await AsyncStorage.setItem(`L2_tranHistory_${chainID}_${address}`,JSON.stringify(res));
        return {success:true}
    }
    //不存在新添加
    res.toAddressList.push(toAddressInfo);
    res.toAddressList.sort(function (x, y) {
        return Number(x.timestamp)-Number(y.timestamp);
    })
    await AsyncStorage.setItem(`L2_tranHistory_${chainID}_${address}`,JSON.stringify(res));
    return {success:true};
}
//移除   转账历史的转账对象
export const removeTranHistoryToAddress = async (chainID: string, address: string, toAddress:string) => {
    let tranHistoryStr = await AsyncStorage.getItem(`L2_tranHistory_${chainID}_${address}`);
    if(!tranHistoryStr)
    {
        return {success:false,falseReason:"地址还未进行交易"};
    }
    let res:tranHistoryType = JSON.parse(tranHistoryStr);
    let index = res.toAddressList.findIndex((item)=>{return item.toAddress === toAddress})
    //如果已存在
    if(index >= 0)
    {
        res.toAddressList.splice(index,1)
        await AsyncStorage.setItem(`L2_tranHistory_${chainID}_${address}`,JSON.stringify(res));
        return {success:true}
    }
    //不存在
    return {success:false,falseReason:"地址不存在该用户的交易历史里面"};
}

//添加  交易记录到用户数据里面
export const addTranToTranHistory = async (isToken:boolean, hash:string, chainID:string, from:string, to:string, timeStamp:string) => {
    console.log(`addTranToTranHistory`,isToken,hash,chainID,from,to,timeStamp)
    let res = await addTranHistoryHashList(chainID,from,hash);
    if(!res.success)
    {
        return res;
    }
    res = await addTranHistoryToAddress(chainID,from,{toAddress:to,timestamp:timeStamp});
    if(!res.success)
    {
        return res;
    }
    return {success:true}
}
//移除 交易记录 暂不需要

//------------------------------------------------联系人与通讯簿-----通讯录------------------

//唯一Key `L2_addressBookNameList`
export type addressBookNameListType = string[];

//获取   地址簿的名称数据
export const getAddressBookNameList = async () => {
    let addressBookListStr = await AsyncStorage.getItem(`L2_addressBookNameList`);
    let res:addressBookNameListType = [];
    if(addressBookListStr)
    {
        res = JSON.parse(addressBookListStr);
    }
    return res;
}
//添加   地址簿的名称数据
export const addAddressBookNameList = async (name:string) => {
    try {
        if (!name) {
            return {success: false, falseReason: "请输入地址簿名称"}
        }
        let addressBookNameListTemp = await getAddressBookNameList();
        if (addressBookNameListTemp.indexOf(name) >= 0) {
            return {success: false, falseReason: "地址簿名称已存在"}
        }
        addressBookNameListTemp.push(name);
        await AsyncStorage.setItem(`L2_addressBookNameList`, JSON.stringify(addressBookNameListTemp));
        return {success:true}
    }catch (e) {
        return {success: false, falseReason: "请重新添加地址簿名称"}
    }
}
//移除   地址簿的名称数据
export const removeAddressBookNameList = async (name:string) => {
    try {
        if (!name) {
            return {success: false, falseReason: "请输入地址簿名称"}
        }
        let addressBookNameListTemp = await getAddressBookNameList();
        let index = addressBookNameListTemp.indexOf(name);
        if ( index === -1) {
            return {success: false, falseReason: "地址簿名称不存在"}
        }
        addressBookNameListTemp.splice(index,1);
        await AsyncStorage.setItem(`L2_addressBookNameList`, JSON.stringify(addressBookNameListTemp));
        return {success:true}
    }   catch (e) {
        return {success: false, falseReason: "请重新移除地址簿名称"}
    }
}

//唯一Key `L2_addressBook_${name}`
export type addressBookType = {
    name:string,
    remark:string,
    bookAddressList:bookAddressType[],
    chainIDList:string[],
    timestamp:number
}
export type bookAddressType = {
    address:string,
    chainID:string,
    chainName:string,
}

//添加   地址簿的数据(地址)
export const addAddressBook_address = async (name:string,bookAddress:bookAddressType) => {
    try {
        if ( !bookAddress ) {
            return {success: false, falseReason: "请输入地址信息"}
        }
        let addressBookTemp = await getAddressBook(name);
        let index = addressBookTemp.bookAddressList.findIndex((item) => {
            return item.address === bookAddress.address && item.chainID === bookAddress.chainID;
        })
        if(index >= 0)
        {
            return {success: false, falseReason: "地址信息已存在"}
        }
        let indexChainID = addressBookTemp.chainIDList.findIndex((item) => {
            return item === bookAddress.chainID;
        })
        if(indexChainID === -1)
        {
            addressBookTemp.chainIDList.push(bookAddress.chainID);
        }
        addressBookTemp.bookAddressList.push(bookAddress);
        await AsyncStorage.setItem(`L2_addressBook_${name}`,JSON.stringify(addressBookTemp));
        return {success:true};
    }catch (e) {
        return {success: false, falseReason: "请重新添加地址"}
    }
}
//移除   地址簿的数据（地址）
export const removeAddressBook_address = async (name:string,bookAddress:bookAddressType) => {
    try {
        if ( !bookAddress ) {
            return {success: false, falseReason: "请输入地址信息"}
        }
        let addressBookTemp = await getAddressBook(name);
        let index = addressBookTemp.bookAddressList.findIndex((item) => {
            return item.address === bookAddress.address && item.chainID === bookAddress.chainID;
        })
        if(index === -1)
        {
            return {success: false, falseReason: "地址信息不存在"}
        }
        addressBookTemp.bookAddressList.splice(index,1);
        let indexChainID = addressBookTemp.bookAddressList.findIndex((item) => {
            return item.chainID === bookAddress.chainID;
        })
        //没有相同chainID的地址了
        if(indexChainID === -1)
        {
            let indexTemp = addressBookTemp.chainIDList.findIndex((item) => {
                return item === bookAddress.chainID
            })
            if(indexTemp >= 0)
            {
                addressBookTemp.chainIDList.splice(indexTemp,1);
            }
        }
        await AsyncStorage.setItem(`L2_addressBook_${name}`,JSON.stringify(addressBookTemp));
        return {success:true};
    }catch (e) {
        return {success: false, falseReason: "请重新删除地址"}
    }
}

//获取   地址簿
export const getAddressBook = async (name:string) => {
    let addressBookStr = await AsyncStorage.getItem(`L2_addressBook_${name}`);
    let res:addressBookType = {name,remark:"",bookAddressList:[],chainIDList:[]};
    if(addressBookStr)
    {
        res = JSON.parse(addressBookStr);
    }
    return res;
}
//添加   地址簿
export const addAddressBook = async (addressBook:addressBookType) => {
    if(!addressBook)
    {
        return { success: false, falseReason:"请输入添加新的地址簿信息" }
    }
    try {
        if (addressBook.bookAddressList.length > 0) {
            for (let i = 0; i < addressBook.bookAddressList.length; i++) {
                let addAddressBook_addressRes = await addAddressBook_address(addressBook.name, addressBook.bookAddressList[i]);
                if (!addAddressBook_addressRes.success) {
                    return addAddressBook_addressRes;
                }
            }
        }
        let addAddressBookNameListRes = await addAddressBookNameList(addressBook.name);
        if (!addAddressBookNameListRes.success) {
            return addAddressBookNameListRes
        }
        await AsyncStorage.setItem(`L2_addressBook_${addressBook.name}`,JSON.stringify(addressBook));
        return {success: true}
    }catch (e) {
        return {success: false,falseReason:e.message}
    }
}
//移除   地址簿
export const removeAddressBook = async (name:string) => {
    if(!name)
    {
        return {success: false,falseReason:"请输入要移除的地址簿名称"}
    }
    try {
        let addressBook = await getAddressBook(name)
        for(let i = 0 ; i < addressBook.bookAddressList.length ; i++)
        {
            let removeAddressBook_addressRes = await removeAddressBook_address(name,addressBook.bookAddressList[i]);
            if(!removeAddressBook_addressRes.success)
            {
                return removeAddressBook_addressRes
            }
        }
        let addAddressBookNameListRes = await removeAddressBookNameList(addressBook.name);
        if (!addAddressBookNameListRes.success) {
            return addAddressBookNameListRes
        }
        await AsyncStorage.removeItem(`L2_addressBook_${name}`);
        return {success: true}
    }catch (e) {
        return {success: false,falseReason:e.message}
    }
}

//更新   地址簿的数据（名字）
export const updateAddressBook_name = async (name:string,newName:string) => {
    let addressBookTemp = await getAddressBook(name);
    addressBookTemp.name = newName;
    let addAddressBookRes = await addAddressBook(addressBookTemp)
    if(!addAddressBookRes.success)
    {
        return addAddressBookRes
    }
    let removeAddressBookRes = await removeAddressBook(name)
    if(!removeAddressBookRes.success)
    {
        await removeAddressBook(addressBookTemp.name)
        return removeAddressBookRes
    }

    return {success:true}
}
//更新   地址簿的数据（备注）
export const updateAddressBook_remark = async (name:string,newRemark:string) => {
    let addressBookTemp = await getAddressBook(name);
    addressBookTemp.remark = newRemark;
    let removeAddressBookRes = await removeAddressBook(name)
    if(!removeAddressBookRes.success)
    {
        return removeAddressBookRes
    }
    let addAddressBookRes = await addAddressBook(addressBookTemp)
    if(!addAddressBookRes.success)
    {
        return addAddressBookRes
    }
    return {success:true}
}





